package com.hmdp.intercepter;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

@Slf4j
@Component
public class loginInterceptor implements HandlerInterceptor {
    @Autowired
    private  RedisTemplate<String, Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("loginInterceptor---------生效");
        String token = request.getHeader("authorization");
        log.info("token:{}",token);
        //2.获取redis中的用户
        String key  = LOGIN_USER_KEY + token;
        Map<Object,Object> user = redisTemplate.opsForHash().entries(key);
        //3.判断用户是否存在
        if(user.isEmpty()){
            //4.不存在，拦截，返回401状态码
            response.setStatus(401);
            return false;
        }
        //5.存在，保存用户信息到Threadlocal
        UserDTO userDTO = BeanUtil.fillBeanWithMap(user, new UserDTO(), false);
        log.info("保存用户信息成功:{}",userDTO);
        UserHolder.saveUser(userDTO);
        //刷新token有效期
        redisTemplate.expire(key,30, TimeUnit.MINUTES);
        //6.放行
        return true;
    }
}
